<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <h2>商城管理系统</h2>
      </template>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="0"
        @keyup.enter="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="form.username"
            placeholder="用户名"
            prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            class="login-button"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/modules/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const formRef = ref(null)
const loading = ref(false)

const form = reactive({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!formRef.value) return
  
  try {
    // 表单验证
    await formRef.value.validate()
    loading.value = true
    
    console.log('开始登录流程')
    
    // 登录
    const loginResult = await userStore.login({
      username: form.username,
      password: form.password
    })
    console.log('登录成功，结果:', { ...loginResult, token: '***' })
    
    // 获取用户信息
    const userInfo = await userStore.getUserInfo()
    console.log('获取用户信息成功:', userInfo)
    
    // 登录成功提示
    ElMessage.success('登录成功')
    
    // 跳转到目标页面
    const redirect = route.query.redirect || '/'
    console.log('准备跳转到:', redirect)
    await router.push(redirect)
  } catch (error) {
    console.error('登录失败，详细错误:', error)
    
    // 根据错误类型显示不同的错误信息
    if (error.response) {
      // 服务器返回的错误
      const { status, data } = error.response
      if (status === 401) {
        ElMessage.error('用户名或密码错误')
      } else if (status === 429) {
        ElMessage.error('登录尝试次数过多，请稍后再试')
      } else {
        ElMessage.error(data?.message || '登录失败，请稍后重试')
      }
    } else if (error.message) {
      // 自定义错误消息
      ElMessage.error(error.message)
    } else {
      // 其他错误
      ElMessage.error('登录失败，请检查网络连接')
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
}

.login-card :deep(.el-card__header) {
  text-align: center;
  padding: 20px;
}

.login-card h2 {
  margin: 0;
  font-size: 24px;
}

.login-button {
  width: 100%;
}
</style> 